<?php
define('IN_ECS', true);

require(dirname(__FILE__) . '/includes/init.php');
require_once('./admin/includes/Response.php');
require_once('./includes/picture.php');
$action  = isset($_REQUEST['act']) ? trim($_REQUEST['act']) : 'default';

if ($action == 'act_register') {
    $username = isset($_REQUEST['user_name']) ? trim($_REQUEST['user_name']) : '';
    $birth = isset($_REQUEST['birth']) ? trim($_REQUEST['birth']) : '';
    $address = isset($_REQUEST['address']) ? trim($_REQUEST['address']) : '';
    $sex = isset($_REQUEST['sex']) ? trim($_REQUEST['sex']) : '';
    $user_pic = $uploadfile;
    $password = isset($_REQUEST['password']) ? trim($_REQUEST['password']) : '';
    $phone = isset($_REQUEST['phone']) ? trim($_REQUEST['phone']) : '';
    $joindate = date('Ymd');

    if (empty($username)) {
        return Response::json(401, "用户名不能为空", $username);
    }
    else if (mb_strlen($username,'UTF8')  > 10){
            return Response::json(409,"用户名长度长度不可超过10位",$username);
        }
    if (empty($birth)) {
        return Response::json(402, "生日不能为空", $birth);
    }
    if (empty($address)) {
        return Response::json(403, "常住地不能为空", $address);
    }
    if (empty($sex)) {
        return Response::json(404, "性别不能为空", $sex);
    }
    if (empty($user_pic)) {
        return Response::json(405, "头像不能为空",$user_pic);
    }
    if(empty($phone)){
        return Response::json(406,"手机号不能为空",$phone);
    } else if (!is_numeric($phone)||strlen($phone) != 11) {
            return Response::json(413, "手机号不合法", $phone);
        } else if (user_is_exist($phone)) {
                return Response::json(408, "该手机号已被注册", $phone);
            }

    if (strlen($password) < 6)
    {
        Response::json(411,"密码长度不能小于6位",$password);
    }

    if (strpos($password, ' ') > 0)
    {
        Response::json(412,"密码不合法",$password);
    }
    $random=rand(1,9999);
    $password=md5(md5($password).$random);
    $sql = "INSERT INTO ". $ecs->table('user') . " (user_name, birth,address,user_sex,user_pic,phone,password,random,join_date)". VALUES."('$username','$birth','$address','$sex','$user_pic','$phone','$password','$random','$joindate')" ;
    $db->query($sql);
    $rows = mysql_affected_rows();
    $sql = "SELECT * FROM ".$ecs->table('user')."WHERE phone ='$phone'";
    $row = $db->getRow($sql);

    if($rows > 0){
        Response::json(201,"数据上传成功",$row);
    }
    else{
        Response::json(430,"数据上传失败",$row);
    }


}
function user_is_exist($phone){
    $sql = "SELECT user_name FROM ".$GLOBALS['ecs']->table('user')."WHERE phone ='$phone'";
    $result = $GLOBALS['db']->query($sql);
    $rows = mysql_num_rows($result);
    if($rows > 0){
        return ture;
    }
    else{
        return false;
    }



}